<template>
  <view class="container">
    <view class="header">
      <view class="title">我的评价</view>
    </view>
    
    <view v-if="loading" class="loading">
      <view class="loading-spinner"></view>
      <text>加载中...</text>
    </view>
    
    <view v-else-if="reviews.length === 0" class="empty-state">
      <image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
      <text class="empty-text">暂无评价内容</text>
    </view>
    
    <view v-else class="reviews-list">
      <view v-for="review in reviews" :key="review.id" class="review-item">
        <view class="product-info">
          <image :src="product.mainImage || '/static/images/default-category.png'" class="product-image" mode="aspectFill"></image>
          <view class="product-details">
            <text class="product-name">{{ product.name }}</text>
            <text class="product-specs">{{ review.specifications || '默认规格' }}</text>
          </view>
        </view>
        
        <view class="review-content">
          <view class="rating-row">
            <view class="star-rating">
              <text v-for="i in 5" :key="i" class="star" :class="{ 'active': i <= review.rating }">★</text>
            </view>
            <text class="review-date">{{ formatDate(review.createdAt) }}</text>
          </view>
          <text class="review-text">{{ review.comment }}</text>
          <view class="review-images" v-if="review.images && formatImages(review.images).length > 0">
            <image 
              v-for="(image, index) in formatImages(review.images)" 
              :key="index" 
              :src="image" 
              class="review-image" 
              mode="aspectFill"
              @click="previewImage(formatImages(review.images), index)"
            ></image>
          </view>
        </view>
        
        <view class="actions">
          <view class="action-btn" @click="deleteReview(review.id)">删除</view>
          <view class="action-btn edit" @click="editReview(review)">修改</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad,onShow } from '@dcloudio/uni-app';
import { reviewApi,productApi } from '../../api/index.js';

// 响应式数据
const orderId = ref(null);
const reviews = ref([]);
const loading = ref(true);
const product = ref(null)

// 接收页面参数
onLoad((options) => {
  if (options.orderId) {
    orderId.value = options.orderId;
  } else {
    loading.value = false;
    uni.showToast({
      title: '订单ID不存在',
      icon: 'none'
    });
  }
});

onShow(() =>{
	loadReviews();
})

// 加载评价
const loadReviews = async () => {
  loading.value = true;
  try {
	  
    const res = await reviewApi.getMyReviews();
	
    
    if (res.code === 200) {
      // 过滤出当前订单的评价
      const orderReviews = res.data.filter(review => review.orderId === parseInt(orderId.value));
	  if(orderReviews && orderReviews.length!=0){
		  const result = await productApi.getProductById(orderReviews[0].productId);
		  product.value = result.data
	  }
      reviews.value = orderReviews;
    } else {
      uni.showToast({
        title: '获取评价失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('加载评价失败:', error);
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  try {
    const date = new Date(dateString.replace(/-/g, '/').replace('T', ' ').split('.')[0]);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  } catch (e) {
    console.error('日期格式化错误:', e);
    return dateString;
  }
};

// 预览图片
const previewImage = (images, index) => {
  uni.previewImage({
    urls: images,
    current: index
  });
};

// 格式化图片数组，处理JSON字符串格式
const formatImages = (images) => {
  if (!images) return [];
  
  try {
    if (typeof images === 'string') {
      return JSON.parse(images);
    }
    return images;
  } catch (e) {
    console.error('解析图片数据失败:', e);
    return [];
  }
};

// 删除评价
const deleteReview = (reviewId) => {
  uni.showModal({
    title: '确认删除',
    content: '是否确认删除该评价？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await reviewApi.deleteReview(reviewId);
          if (result.code === 200) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
            // 重新加载评价列表
            loadReviews();
          } else {
            uni.showToast({
              title: '删除失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('删除评价失败:', error);
          uni.showToast({
            title: '删除失败，请重试',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 修改评价
const editReview = (review) => {
  // 构建要传递的参数
  const productInfo = encodeURIComponent(JSON.stringify({
    id: review.productId,
    name: review.productName,
    image: review.productImage
  }));
  
  const specs = encodeURIComponent(review.specifications || '默认规格');
  
  // 跳转到评价编辑页面
  uni.navigateTo({
    url: `/pages/review/edit?reviewId=${review.id}&orderId=${orderId.value}&productInfo=${productInfo}&specs=${specs}`
  });
};
</script>

<style>
.container {
  padding: 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.header {
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #ff6700;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
}

.reviews-list {
  margin-bottom: 30rpx;
}

.review-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.product-info {
  display: flex;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  background-color: #f5f5f5;
}

.product-details {
  flex: 1;
  padding-left: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.product-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.product-specs {
  font-size: 24rpx;
  color: #999;
  background-color: #f8f8f8;
  padding: 6rpx 12rpx;
  border-radius: 6rpx;
  display: inline-block;
}

.review-content {
  margin-bottom: 20rpx;
}

.rating-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.star-rating {
  display: flex;
}

.star {
  font-size: 36rpx;
  color: #ddd;
  margin-right: 6rpx;
}

.star.active {
  color: #ff6700;
}

.review-date {
  font-size: 24rpx;
  color: #999;
}

.review-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
  margin-bottom: 20rpx;
}

.review-images {
  display: flex;
  flex-wrap: wrap;
}

.review-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  margin-right: 15rpx;
  margin-bottom: 15rpx;
}

.actions {
  display: flex;
  justify-content: flex-end;
  border-top: 1rpx solid #f5f5f5;
  padding-top: 20rpx;
}

.action-btn {
  font-size: 26rpx;
  color: #666;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  margin-left: 20rpx;
  background-color: #f5f5f5;
}

.action-btn.edit {
  color: #ff6700;
  background-color: rgba(255, 103, 0, 0.1);
}
</style> 